package com.achievement.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.achievement.domain.dto.ReportAuthorDTO;
import com.achievement.domain.dto.ReportDTO;
import com.achievement.domain.entity.ReportEntity;
import com.achievement.domain.param.ReportParam;
import com.achievement.domain.vo.ReportAuthorVO;
import com.achievement.domain.vo.ReportVO;
import com.achievement.mapper.ReportMapper;
import com.achievement.mappings.ReportMapping;
import com.achievement.service.IAchievementFileService;
import com.achievement.service.IReportAuthorService;
import com.achievement.service.IReportService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.api.ApprovalApi;
import com.common.api.CommonFileApi;
import com.common.core.domain.AjaxResult;
import com.common.utils.DateUtils;
import com.common.utils.QueryWrapperUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.StringUtils;
import com.common.utils.bean.BizProcessMessages;
import com.flowable.domain.vo.task.BpmTaskApproveReqVO;
import com.flowable.service.IFlowTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author CNKI
* @description 针对表【biz_research_report(科研成果-研究报告列表)】的数据库操作Service实现
* @createDate 2025-02-25 15:58:14
*/
@Service
public class ReportServiceImpl extends ServiceImpl<ReportMapper, ReportEntity>
    implements IReportService {

    @Autowired
    private ReportMapping mapping;

    @Autowired
    private IReportAuthorService reportAuthorService;

    @Autowired
    private IAchievementFileService fileService;

    @Autowired
    private ApprovalApi approvalApi;

    //流程引擎
    @Autowired
    private IFlowTaskService flowTaskService;

    //通用文件api
    @Autowired
    private CommonFileApi fileApi;

    private final static String module_name = "研究报告";

    /**
     * 新增研究报告
     *
     * @param dto ReportDTO
     */
    @Override
    public AjaxResult add(ReportDTO dto) {
        String UUID = IdUtil.randomUUID().replace("-", "");

        dto.setId(UUID);

        List<ReportAuthorDTO> authorList = dto.getAuthorList();

        String authorpids = authorList.stream().map(ReportAuthorDTO::getPersonId).collect(Collectors.joining(","));
        String authorunitids = authorList.stream().map(ReportAuthorDTO::getAuthorUnitId).collect(Collectors.joining(";"));

        dto.setAuthorpids(authorpids);
        dto.setAuthorunitids(authorunitids);
        dto.setAuthorNumber(authorList.size());

        //新增研究报告基本信息
        ReportEntity entity = mapping.dto2Entity(dto);


        //新增研究报告作者信息
        //根据研究报告 reportId，删除作者信息，再新增作者信息
        reportAuthorService.deleteByReportId(UUID);

        //给每个作者加上研究报告ID
        for (ReportAuthorDTO reportAuthorDTO : dto.getAuthorList()) {
            reportAuthorDTO.setResearchReportId(UUID);
        }


        Integer submitType = dto.getSubmitType();

        switch (submitType) {
            case 2: // 保存并通过
                entity.setProcessInstanceId("0");
                entity.setCheckstatus(String.valueOf(submitType));
                entity.setCheckdate(DateUtils.getTime());
                entity.setChecker(SecurityUtils.getNickName());
                break;
            case 1: // 提交
                entity.setCheckstatus(String.valueOf(submitType));
                if (!(this.save(entity) && reportAuthorService.add(dto.getAuthorList()))) {
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                String processInstanceId = null;
                try {
                    //发起流程 业务状态由流程引擎更新
                    processInstanceId = approvalApi.businessEntryApproval(entity.getId(), module_name);
                } catch (Exception e) {
                    AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS);
                }

                return StringUtils.isEmpty(processInstanceId)
                        ? AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS)
                        : AjaxResult.success((Object)entity.getId());
            default: // 处理 -1（暂存）及其他情况
                entity.setCheckstatus(String.valueOf(submitType));
                break;
        }

        boolean r = this.save(entity)
                && reportAuthorService.add(dto.getAuthorList());
        return r ? AjaxResult.success((Object)entity.getId()) : AjaxResult.error(BizProcessMessages.SAVE_FAIL);

    }

    /**
     * 删除研究报告
     *
     * @param ids ids
     */
    @Override
    public boolean batchRemove(List<String> ids) {

        List<ReportEntity> list = this.listByIds(ids);
        List<String> fileList = new ArrayList<>();
        //删除记录所携带的文件
        list.forEach(e -> {
            String fileIds = e.getFileIds();
            if (com.common.utils.StringUtils.isNotEmpty(fileIds)) {
                String[] split = fileIds.split(",");
                fileList.addAll(Arrays.asList(split));
            }
        });

        for (String fileId : fileList) {
            fileApi.delFile(fileId);
        }

        //删除作者
        reportAuthorService.deleteByReportIdList(ids);

        return this.removeByIds(ids);
    }

    /**
     * 修改研究报告
     *
     * @param dto ReportDTO
     */
    @Override
    public AjaxResult update(ReportDTO dto) {

        List<ReportAuthorDTO> authorList = dto.getAuthorList();

        String authorpids = authorList.stream().map(ReportAuthorDTO::getPersonId).collect(Collectors.joining(","));
        String authorunitids = authorList.stream().map(ReportAuthorDTO::getAuthorUnitId).collect(Collectors.joining(";"));

        dto.setAuthorpids(authorpids);
        dto.setAuthorunitids(authorunitids);
        dto.setAuthorNumber(authorList.size());

        ReportEntity entity = mapping.dto2Entity(dto);

        //新增研究报告作者信息
        //根据研究报告 reportId，删除作者信息，再新增作者信息
        reportAuthorService.deleteByReportId(entity.getId());

        //给每个作者加上研究报告ID
        for (ReportAuthorDTO reportAuthorDTO : dto.getAuthorList()) {
            reportAuthorDTO.setResearchReportId(entity.getId());
        }

        Integer submitType = dto.getSubmitType();

        switch (submitType) {
            case 2: // 保存并通过
                // 当前用户是否是审批人
                boolean isAuditor = dto.getIsAuditor();
                // 审批人直接审核（仅适用于提交类型2且为当前审核人的情况）
                if (isAuditor) {
                    if (this.updateById(entity)&& reportAuthorService.add(dto.getAuthorList())) {
                        BpmTaskApproveReqVO bta = new BpmTaskApproveReqVO();
                        bta.setId(dto.getTaskId());
                        bta.setReason(SecurityUtils.getNickName() + "保存并通过");
                        try {
                            flowTaskService.approveTask(SecurityUtils.getUserId(), bta);
                        } catch (Exception e) {
                            return AjaxResult.error(BizProcessMessages.SAVE_SUCCESS_APPROVE_FAIL, e.getMessage());
                        }

                        return AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
                    }
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                //处理非当前审批人保存并通过
                if (!dto.getCheckstatus().equals("2")){
                    entity.setProcessInstanceId("0");
                }
                entity.setCheckdate(DateUtils.getTime());
                entity.setChecker(SecurityUtils.getNickName());
                //只有管理员才会有非当前审核人的情况下有 "保存并提交"按钮,审核完后的结果只能是审核通过
                entity.setCheckstatus(String.valueOf(submitType));
                break;
            case 1:
                //暂存转提交
                if (!(this.updateById(entity)&& reportAuthorService.add(dto.getAuthorList()))) {
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                String returnProcessInstanceId = null;
                try {
                    returnProcessInstanceId = approvalApi.businessEntryApproval(entity.getId(), module_name);
                } catch (Exception e) {
                    return AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS, e.getMessage());
                }

                return StringUtils.isEmpty(returnProcessInstanceId)
                        ? AjaxResult.warn(BizProcessMessages.SAVE_PARTIAL_SUCCESS)
                        : AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
            case -1: // 暂存
                return this.updateById(entity) && reportAuthorService.add(dto.getAuthorList())
                        ? AjaxResult.success(BizProcessMessages.SAVE_SUCCESS)
                        : AjaxResult.error(BizProcessMessages.SAVE_FAIL);
            default:
                break;
        }

        return this.updateById(entity) && reportAuthorService.add(dto.getAuthorList())
                ? AjaxResult.success(BizProcessMessages.SAVE_SUCCESS)
                : AjaxResult.error(BizProcessMessages.SAVE_FAIL);
    }

    /**
     * 列表检索
     *
     * @param param ReportParam
     */
    @Override
    public List<ReportVO> selectByPage(ReportParam param) {

        param.setSubmitDateStart(DateUtils.dateStrHandle(param.getSubmitDateStart(), param.getDateFormat(), "start"));
        param.setSubmitDateEnd(DateUtils.dateStrHandle(param.getSubmitDateEnd(), param.getDateFormat(), "end"));

        LambdaQueryWrapper<ReportEntity> queryWrapper = new LambdaQueryWrapper();
        QueryWrapperUtils.getParams_achievement(queryWrapper, SecurityUtils.getLoginUser().getUser());

        List<ReportVO> reportVOList = this.baseMapper.getList(param,queryWrapper);

        //获取当前用户所有的代办列表
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(module_name);

        reportVOList.stream().forEach(a -> {
            // 判断是否是审核人，并设置taskId
            String processInstanceId = a.getProcessInstanceId();
            if (StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
                a.setTaskId(instanceTaskMap.get(processInstanceId));
                a.setIsAuditor(true);
            } else {
                a.setIsAuditor(false);
            }
        });

        return reportVOList;
    }

    /**
     * 左上方统计 通过，退回，待审核
     *
     * @param param
     */
    @Override
    public List<HashMap<String, Integer>> listStatistics(ReportParam param) {
        param.setSubmitDateStart(DateUtils.dateStrHandle(param.getSubmitDateStart(), param.getDateFormat(), "start"));
        param.setSubmitDateEnd(DateUtils.dateStrHandle(param.getSubmitDateEnd(), param.getDateFormat(), "end"));

        LambdaQueryWrapper<ReportEntity> queryWrapper = new LambdaQueryWrapper();
        QueryWrapperUtils.getParams_achievement(queryWrapper, SecurityUtils.getLoginUser().getUser());

        return this.baseMapper.listStatistics(param,queryWrapper);
    }

    /**
     * 研究报告导出
     *
     * @param param ReportParam
     */
    @Override
    public List<ReportVO> getListByConditions(ReportParam param) {
        param.setSubmitDateStart(DateUtils.dateStrHandle(param.getSubmitDateStart(), param.getDateFormat(), "start"));
        param.setSubmitDateEnd(DateUtils.dateStrHandle(param.getSubmitDateEnd(), param.getDateFormat(), "end"));

        LambdaQueryWrapper<ReportEntity> queryWrapper = new LambdaQueryWrapper();
        QueryWrapperUtils.getParams_achievement(queryWrapper, SecurityUtils.getLoginUser().getUser());

        List<ReportVO> reportVOList = this.baseMapper.getListByConditions(param,queryWrapper);

        return reportVOList;
    }

    /**
     * 获取研究报告详细信息
     *
     * @param id id
     */
    @Override
    public ReportVO getInfoById(String id) {
        ReportEntity entity = this.getById(id);
        if (ObjectUtil.isNull(entity)){
            return new ReportVO();
        }

        ReportVO reportVO = mapping.entity2Vo(entity);

        //查询研究报告作者列表信息
        List<ReportAuthorVO> authorVOList = reportAuthorService.getInfoByReportId(id);

        reportVO.setAuthorList(authorVOList);

        //附件信息
        String fileIds = entity.getFileIds();
        if (StringUtils.hasText(fileIds)) {
            String[] fileIdArr = fileIds.split(",");
            List<Map<String,String>> fileInfo = fileService.getFileInfoByFileIds(fileIdArr);
            reportVO.setFileList(fileInfo);
        }

        //获取当前用户所有的代办列表
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(module_name);
        // 判断是否是审核人，并设置taskId
        String processInstanceId = reportVO.getProcessInstanceId();
        if (StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
            reportVO.setTaskId(instanceTaskMap.get(processInstanceId));
            reportVO.setIsAuditor(true);
        } else {
            reportVO.setIsAuditor(false);
        }


        return reportVO;
    }

    @Override
    public void updateBusinessStatus(String tableName, String businessId, String checkStatus, String sysUserId) {
        if (StringUtils.isEmpty(tableName) || StringUtils.isEmpty(businessId) || StringUtils.isEmpty(checkStatus))
            return;
        ReportEntity entity = new ReportEntity();
        entity.setId(businessId);
        entity.setCheckstatus(checkStatus);
        if ("2".equals(checkStatus)) {
            entity.setCheckdate(DateUtils.getTime());
            entity.setChecker(SecurityUtils.getNickName());
        }
        this.updateById(entity);
    }
}